﻿
$nuspecFiles = @(
#    "../Source/Core/WindowsPhoneCore/Calcium.WindowsPhone.nuspec", 
#    "../Source/Core/WindowsPhone.XamarinForms/Calcium.XamarinForms.WindowsPhone.nuspec",
#    "../Source/Core/AndroidCore/Calcium.Android.nuspec",
#    "../Source/Core/IosCore/Calcium.Ios.nuspec",
#   "../Source/Core/Core/Calcium.Wpf.nuspec",
#	"../Source/Calcium/Xamarin/NuGet/Calcium.XamarinForms.nuspec",
#	"../Source/Core/UwpCore/Calcium.Uwp.nuspec",
	"../Deployment/Calcium.nuspec")

$solutionsToBuild = @("C:\CodePlex\Calcium\Trunk\Source\Calcium\Xamarin\Installation\CalciumTemplates.Xamarin.sln")

#Import-Module Invoke-MsBuild

#foreach ($solution in $solutionsToBuild)
#{
#    Write-Host "Building solutions " + $solution 
#    if ((Invoke-MsBuild -Path $solution) -eq $true) 
#    { 
#        Write-Host "Build completed." 
#    } 
#    else 
#    { 
#        throw "Solution " + $solution + " failed to build."
#        Exit
#    }
#}

$assemblyToEnsureJustBuilt = @(
 #   "../Source/Core/WindowsPhoneCore/Bin/Release/Outcoder.Calcium.WindowsPhone.dll",
 #   "../Source/Core/WindowsPhone.XamarinForms/Bin/Release/Outcoder.Calcium.dll",
	"../Source/Core/AndroidCore/bin/Release/Outcoder.Calcium.Android.dll",
	"../Source/Core/IosCore/bin/iPhoneSimulator/Release/Outcoder.Calcium.Ios.dll",
	"../Source/Core/Core/bin/Release/Outcoder.Calcium.dll",
	"../Source/Core/UwpCore/bin/Release/Outcoder.Calcium.dll")

$mustBeBuiltAfter = [DateTime]::Now.AddMinutes(-15)

foreach ($assembly in $assemblyToEnsureJustBuilt)
{
	$filePath = $PSScriptRoot + "/" + $assembly
	$file = Get-ChildItem -Path $filePath

	if ($file.LastWriteTime -lt $mustBeBuiltAfter)
	{
		throw "Assembly was not built recently enough. " + $file.FullName
		Exit
	}
}

function Pack-NuGetFiles
{
  Param
  (
	[string]$PackageVersion = "1.0.J.B",
	[string]$NugetPath = "NuGet.exe",
	[string]$localNugetDirectory = "C:\Development\NuGetLocalFeed"
  )
	 
	$buildNumber = $env:TF_BUILD_BUILDNUMBER
	if ($buildNumber -eq $null)
	{
		$buildIncrementalNumber = 0
	}
	else
	{
		$splitted = $buildNumber.Split('.')
		$buildIncrementalNumber = $splitted[$splitted.Length - 1]
	}
	 
	Write-Host "Executing Publish-NugetPackage in path $SrcPath, PackageVersion is $PackageVersion"

	$jan1 = Get-Date 1/1
	$today = Get-Date
	$jdate = ($today - $jan1).days
	$buildIncrementalNumber = $today.Hour * 60 + $today.Minute
	#$julian.ToString("000")
	 
	#$jdate = Get-JulianDate
	$PackageVersion = $PackageVersion.Replace("J", $jdate).Replace("B", $buildIncrementalNumber)
	 
	Write-Host "Transformed PackageVersion is $PackageVersion "
  
	$AllNuspecFiles = $nuspecFiles 
			# Get-ChildItem $SrcPath*.nuspec
   
	#Remove all previous packed packages in the directory
	  
	$AllNugetPackageFiles = Get-ChildItem $SrcPath*.nupkg
   
	foreach ($file in $AllNugetPackageFiles)
	{ 
		Remove-Item $file
	}

	#$scriptPath = $PSScriptRoot
	#$scriptDir = $PSScriptRoot
 
	foreach ($fileName in $AllNuspecFiles)
	{ 
		#Write-Host "Modifying file " + $file.FullName
		#save the file for restore
		#$backFile = $file.FullName + "._ORI"
		#$tempFile = $file.FullName + ".tmp"
		#Copy-Item $file.FullName $backFile -Force
		#now load all content of the original file and rewrite modified to the same file
		#Get-Content $file.FullName |
		#%{$_ -replace '<version>[0-9]+(.([0-9]+|*)){1,3}</version>', "<version>$PackageVersion</version>" } > $tempFile
		#Move-Item $tempFile $file.FullName -force

		$filePath = $PSScriptRoot + "/" + $fileName
		$file = Get-ChildItem -Path $filePath
 
		#Create the .nupkg from the nuspec file
		$ps = new-object System.Diagnostics.Process
		$ps.StartInfo.Filename = "$NugetPath"
		$ps.StartInfo.Arguments = "pack `"$file`" -version $PackageVersion"
		$ps.StartInfo.WorkingDirectory = $file.Directory.FullName
		$ps.StartInfo.RedirectStandardOutput = $True
		$ps.StartInfo.RedirectStandardError = $True
		$ps.StartInfo.UseShellExecute = $false
		$ps.start()
		if(!$ps.WaitForExit(30000)) 
		{
			$ps.Kill()
		}
		[string] $Out = $ps.StandardOutput.ReadToEnd();
		[string] $ErrOut = $ps.StandardError.ReadToEnd();
		Write-Host "Nuget pack Output of commandline " + $ps.StartInfo.Filename + " " + $ps.StartInfo.Arguments
		Write-Host $Out
		if ($ErrOut -ne "") 
		{
			Write-Error "Nuget pack Errors"
			Write-Error $ErrOut
		}
		else
		{
			$pathQuery = $file.Directory.ToString() + "/*" + $PackageVersion + ".nupkg"
			$packageFile = Get-ChildItem -Path $pathQuery
			$newPath = $localNugetDirectory + "/" + $packageFile.Name

			Move-Item $packageFile $newPath -force
		}
		#Restore original file
		#Move-Item $backFile $file -Force


	}
	 
	$AllNugetPackageFiles = Get-ChildItem $SrcPath*.nupkg
   
	foreach ($file in $AllNugetPackageFiles)
	{ 
		#Create the .nupkg from the nuspec file
		
		#$ps = new-object System.Diagnostics.Process
		#$ps.StartInfo.Filename = "$NugetPathnuget.exe"
		#$ps.StartInfo.Arguments = "push `"$file`" -s $NugetServer $NugetServerPassword"
		#$ps.StartInfo.WorkingDirectory = $file.Directory.FullName
		#$ps.StartInfo.RedirectStandardOutput = $True
		#$ps.StartInfo.RedirectStandardError = $True
		#$ps.StartInfo.UseShellExecute = $false
		#$ps.start()
		#if(!$ps.WaitForExit(30000)) 
		#{
		#    $ps.Kill()
		#}
		#[string] $Out = $ps.StandardOutput.ReadToEnd();
		#[string] $ErrOut = $ps.StandardError.ReadToEnd();
		#Write-Host "Nuget push Output of commandline " + $ps.StartInfo.Filename + " " + $ps.StartInfo.Arguments
		#Write-Host $Out
		#if ($ErrOut -ne "") 
		#{
		#    Write-Error "Nuget push Errors"
		#    Write-Error $ErrOut
		#}
 
	}
}

Pack-NuGetFiles "1.0.26"
Invoke-Item "C:\Development\NuGetLocalFeed"